/**
 * Copyright(C) 2008 Matthias Braunhofer
 * All rights reserved
 *
 * Created on: 28.07.2008
*/

package it.cums.ui.wizards;

import it.cums.core.controller.ApplicationController;
import it.cums.core.model.Products;
import it.cums.core.util.Converter;
import it.cums.core.util.ProductManager;
import it.cums.ui.Activator;
import it.cums.ui.localization.Messages;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;

public class ProductWizard extends Wizard implements IWorkbenchWizard {
	private ProductWizardPage productWizardPage;
	private ApplicationController appController = ApplicationController.getInstance();
	
	public ProductWizard() {
		super();
		setNeedsProgressMonitor(true);
		setWindowTitle(Messages.ProductWizard_0);
	}

	
	public void addPages() {
		// TODO Auto-generated method stub
		productWizardPage = new ProductWizardPage();
		addPage(productWizardPage);
	}
	
	
	public boolean performFinish() {
		Products products = appController.getProducts();
		try {
			ProductManager.getInstance().createAndStoreProduct(products, productWizardPage.getName(), getAvailableQuantity(), getPurchasingPrice(), 
															   getIva(), productWizardPage.getManufacturer(), getSalesPrice(), productWizardPage.getNotes()); 
			return true;
		} catch (Exception e) {
			Activator.getDefault().logError(e.getMessage(), e);
			return false;
		}
	}
	
	private int getAvailableQuantity() {
		String quantity = productWizardPage.getAvailableQuantity();
		if (quantity.equals("")) { //$NON-NLS-1$
			return -1;
		} else {
			return Converter.convertToInteger(quantity);
		}
	}
	
	private double getPurchasingPrice() {
		String price = productWizardPage.getPurchasingPrice();
		if (price.equals("")) { //$NON-NLS-1$
			return -1;
		} else {
			return Converter.convertToDouble(price);
		}
	}
	
	private int getIva() {
		String iva = productWizardPage.getIva();
		return Converter.convertToInteger(iva);
	}
	
	private double getSalesPrice() {
		String price = productWizardPage.getSalesPrice();
		return Converter.convertToDouble(price);
	}

	
	public void init(IWorkbench arg0, IStructuredSelection arg1) {
	}
}
